package com.wyj.controller;

import com.wyj.dao.DepartmentDao;
import com.wyj.dao.EmployeeDao;
import com.wyj.entities.Department;
import com.wyj.entities.Employee;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.sound.midi.Soundbank;
import java.util.Collection;

/**
 * Created by wuyj on 2018/7/2 0002.
 */
@Controller
public class EmpController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @GetMapping("/emps")
    public String getEmployees(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddEmpPage(Model model) {
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departs", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println(employee.toString());
        employeeDao.save(employee);
        return "redirect:/emps";
    }


    @GetMapping("/emp/{id}")
    public String toEditEmpPage(@PathVariable("id")Integer id, Model model) {
        Employee emp = employeeDao.get(id);
        model.addAttribute("emp", emp);
        //获取部门的列表
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departs", departments);
        return "emp/add";
    }

    /**
     * 修改员工
     * @param employee
     * @return
     */
    @PutMapping("/emp")
    public String updateEmp(Employee employee) {
        System.out.println(employee.toString());
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 删除员工
     * @param id
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public String delEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }

}
